package com.xiye.common.util;

import com.xiye.common.controller.BaseController;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


/**
 * @author 西野
 * @version V1.0
 * @title FileUtil.java
 * @package com.xiye.common.util
 * @description 文件处理
 * @date 2018-07-20
 */
@SuppressWarnings("resource")
public class FileUtil extends BaseController {

    /*
     * @Author 西野
     * @Date 2018-07-20 16:13:54
     * @Description 读取到字节数组2
     * @Param [filePath]
     * @Return byte[]
     */
    public static byte[] toByteArray2(String filePath) throws IOException {
        File f = new File(filePath);
        if (!f.exists()) {
            throw new FileNotFoundException(filePath);
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                // do nothing
                // System.out.println("reading");
            }
            return byteBuffer.array();
        } catch (IOException e) {
            LoggerUtil.error(e.toString(), e);
            throw e;
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException e) {
                LoggerUtil.error(e.toString(), e);
            }
            try {
                if (fs != null) {
                    fs.close();
                }
            } catch (IOException e) {
                LoggerUtil.error(e.toString(), e);
            }
        }
    }
}
